package com.wenkang.stu.service;

import com.wenkang.stu.enums.ExceptionEnums;
import com.wenkang.stu.exception.KangException;
import com.wenkang.stu.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginService {

    @Autowired
    private UserDetailsService userDetailsService;

    public String login(String username, String password) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (Objects.nonNull(userDetails)) {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            // 生成token
            return JwtUtils.generateToken(userDetails);
        }
        throw new KangException(ExceptionEnums.LOGIN_INFO_ERROR);
    }
}
